import {menuList} from '@/utils/menu'
import {loopSearch, searchFirstPath} from '@/utils'

const state = {
    menuList: [], // 菜单集合
    breadCrumbArr: [], // 面包屑集合
    pathMapName: {}, // 路由path对name
    firstRoutePath: '', // 菜单第一个路由
    routePath: '',
    indexPath: [], // 菜单打开层级， 用于面包屑展示
    isCollapse: false, // 菜单是否打开， 默认打开
    tabsArr: [], // 选项卡集合
}

const getters = {
    getMenuList: state => state.menuList,
    getBreadCrumbArr: state => state.breadCrumbArr,
    getPathMapName: state => state.pathMapName,
    getFirstRoutePath: state => state.firstRoutePath,
    getRoutePath: state => state.routePath,
    getIndexPath: state => state.indexPath,
    getIsCollapse: state => state.isCollapse,
    getTabsArr: state => state.tabsArr,
}

const actions = {
    // 异步获取菜单
    setMenuList({commit}){
        return new Promise((resolve)=>{
            // 模拟异步请求菜单
            setTimeout(()=>{
                commit('setMenuList', menuList)
                commit('setFirstRoutePath', searchFirstPath(menuList.length ? menuList[0] : {}))
                commit('setPathMapName', loopSearch(menuList, {}, true))
                resolve(menuList)
            }, 2000)
        })
    },
    // 获取选项卡
    setTabsArr({commit, state}, {route, newRoute}){
        const tabsArr = state.tabsArr
        const breadCrumbObj = state.pathMapName
        const selRoute = tabsArr.filter(item=>item.path == newRoute)
        if(!selRoute.length){
            tabsArr.push({
                path: newRoute,
                name: breadCrumbObj[newRoute],
                isClosed: route.meta && route.meta.isClosed || false
            })
            commit('setTabsArr', tabsArr)
        }
    }
}

const mutations = {
    setMenuList(state, value) {
        state.menuList = value
    },
    setBreadCrumbArr(state, value) {
        state.breadCrumbArr = value
    },
    setPathMapName(state, value) {
        state.pathMapName = value
    },
    setFirstRoutePath(state, value) {
        state.firstRoutePath = value
    },
    setRoutePath(state, value) {
        state.routePath = value
    },
    setIndexPath(state, value) {
        state.indexPath = value
    },
    setIsCollapse(state, value) {
        state.isCollapse = value
    },
    setTabsArr(state, value) {
        state.tabsArr = value
    },
}
export default {
    state,
    getters,
    actions,
    mutations
}